<template>
	<view class="page" :style="{'overflow':show?'hidden':''}">
		<view class="answer">
			<view class="answer-textarea">
				<textarea :value="creativeResults" :maxlength="-1" class="answer-textarea-input"></textarea>
				<!-- <view class="answer-textarea-input">
				{{creativeResults}}
			</view> -->
				<view class="answer-fontLength">共{{creativeResults.length}}字</view>
				<view class="answer-bott">
					AI生成仅供参考
				</view>
			</view>
		</view>
		<view class="tabbar">
			<view class="tabbar-item" @click="clickTab(item,index)" v-for="(item, index) in tabbarList" :key="index">
				<view style="font-size: 30rpx;">{{item.text}}</view>
			</view>
		</view>
	</view>
	<!--  进度条  -->
	</view>
</template>

<script>
	import * as TextEncoding from 'text-encoding-shim';
	import cryptoJs from '@/utils/encryptDES.js'
	import {
		myShowLoading,
		myHideLoading,
	} from "../../utils/showToast.js";
	import {
		isLogin,
		vipType
	} from '@/business/login.js';
	import {
		wxTextDetection
	} from "../../utils/textCheck.js";
	import {
		wycUrl,
		wycUrlApi,
		black
	} from '@/api/assemb.js'
	import store from '../../store/idnex.js'
	import config from "../../uni_modules/uview-ui/libs/config/config.js";
	import {
		apiMixUrlApi
	} from "../../api/assemb";

	function hasDuplicateSubstring(str, substring) {
		const regex = new RegExp(substring, 'g'); // 创建一个全局搜索的正则表达式  
		const matches = str.match(regex); // 使用match方法查找所有匹配项  
		return matches && matches.length > 1; // 如果有匹配项且数量大于1，则返回true，否则返回false  
	}
	var diff = require('diff');
	let app = getApp();
	export default {
		data() {
			return {
				tabbarList: [

					{
						src: '/static/create/create_continue1.png',
						text: '复制结果'
					},
					{
						src: '/static/create/create_copy1.png',
						text: '保存结果'
					}
				],
				showMore: false, //分享结果的弹窗
				relativeScale: '',
				canvasPath: '',
				imageWidth: 316,
				imageHeight: 575,
				creatImg: '',
				erCode: '',
				ercodeImg: '',
				creativeResults: '',
				writing: '',
				lenth: true,
				showCanvas: false,
				canvasHeight: 500,
				canvasWidth: 300,
				isVip: false,
				content: '您还不是会员,此功能需开通会员才可使用。',
				compareResults: [],
				vipShow: false,
				frequency: uni.getStorageSync('frequency'),
				aiLevel: 1,
				originality: 0,
				width: 0,
				arrIndex: [],
				widthIndex: 0,
				schedule: 0,
				scheduleShow: false,
				time: null,
				pos: '',
				Liupaer: false,
				ptt: '',
				typingQueue: [],
				isTyping: false,
				outline:'',
				title:'',
				param:{}
			};
		},
		onShow() {
			console.log(getApp().globalData.Liupaer)
			// this.isVip = true;
			// this.posters()
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
		},
		onLoad(options) {
			let para = decodeURIComponent(options.param);
			
			// 将字符串还原为对象  
			this.param = JSON.parse(para);
			console.log(this.param)
			this.aaa()

			var time = new Date()
			let baseinfo = uni.getStorageSync('baseinfo');
			console.log('baseinfo', baseinfo)
			this.userid = baseinfo.userid

		},
		methods: {
			clickTab(item, index) {
				let that = this
				if (index == 0 && this.Liupaer) {
					that.copyResults()
				} else if (index == 1 && this.Liupaer) {
					that.historical()
				} else {
					uni.showToast({
						title: '请等待当前结果生成',
						icon: 'none'
					})
				}
			},
			//非会员扣次数
			feacter() {
				if (!this.isVip) {
					let param = {
						consumecoins: 1,
						descinfo: '一键创作消耗',
						consumetype: 1,
					}
					apiMixUrlApi(param, '1043', "ConsumeCoins").then(result => {
						console.log(result, '1043返回值');
						uni.setStorageSync('frequency', result.coins)
					});
				}
			},
			historical() {
				let today = new Date();
				let month = today.getMonth() + 1;
				let currentDate = today.getFullYear() + "-" + month + "-" + today.getDate();
				let tooles = {
					title: this.creativeResults,
					time: currentDate
				}
				if (uni.getStorageSync('content')) {
					if (uni.getStorageSync('content').length < 20) {
						let content = uni.getStorageSync('content')
						content.push(tooles)
						uni.setStorageSync('content', content);
					} else if (uni.getStorageSync('content').length = 20) {
						let content = uni.getStorageSync('content').slice(1)
						content.push(tooles)
						uni.setStorageSync('content', content);
					}

				} else {
					console.log('111111111')
					let content = []
					content.push(tooles)
					uni.setStorageSync('content', content);
				}
				uni.showToast({
					title: '保存成功'
				})
			},
			// fn(){
			// 	return this.Liupaer = getApp().globalData.Liupaer
			// },
			async processTypingQueue() {
				let that = this
				if (that.typingQueue.length > 0) {
					that.isTyping = true; // 标记为正在进行打字机效果  
					const dataToProcess = that.typingQueue.shift(); // 获取队列中的第一个数据块并移除它  
					await that.typeWriterEffect(dataToProcess); // 执行打字机效果，并等待它完成  
					that.isTyping = false; // 标记为打字机效果已完成  
					// 递归调用以处理队列中的下一个数据块（如果有的话）  
					if (that.typingQueue.length > 0) {
						that.processTypingQueue();
					} else {
						console.log('结束1')
					}
				}
			},

			// 打字机效果函数，使用async/await确保按顺序执行  
			async typeWriterEffect(text) {
				for (let i = 0; i < text.length; i++) {
					this.creativeResults += text[i];
					// 更新UI，这里假设this.creativeResults是绑定到UI的变量  
					// this.creativeResults = creativeResults;   
					// 等待一段时间以实现打字机效果  
					await new Promise(resolve => setTimeout(resolve, 27)); // 200ms延迟  
				}
			},
			aaa() {
				let that = this
				uni.showLoading({
					title: '创作中'
				})
				const requestTask = wx.request({
					url: 'https://ser.aixiezuo888.com/chat/api/c=1038&v=4&a=' + store.state.appid , // 服务端接口地址
					data: cryptoJs.encrypt(JSON.stringify({
						cmd: "magicChatStream",
						base: wx.getStorageSync("baseinfo"),
						param:that.param
					}), 1038),
					method: 'POST',
					enableChunked: true,
					header: {
						//'content-type': 'application/x-www-form-urlencoded',
						Accept: 'text/event-stream'
					},
					success: (response) => {
						console.log(response, 'res')
						if (response.statusCode == 200 || uni.getStorageSync('OS') == 'windows') {
							console.log(that.creativeResults.length)
							setTimeout(() => {
								that.Liupaer = true
							}, 3000);
							that.feacter()
						} else {
							this.creativeResults = ''
							uni.showToast({
								title: '出错了请重试',
								icon: 'none',
								duration: 2000
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 2000);
						}
					},
					fail: (err) => {
						// 开启enableChunked后，成功的回调一般用不到，因为响应数据不在这里返回
						console.log(err, '失败');
						uni.showToast({
							title: '出错了请重试',
							icon: 'none',
							duration: 2000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 2000);
					}
				});
				requestTask.onChunkReceived((chunk) => {
					const arrayBuffer = chunk.data;
					const uint8Array = new Uint8Array(arrayBuffer);
					const str = new TextEncoding.TextDecoder('utf-8').decode(uint8Array);
					that.pos = str.replace(/data:/g, '');
					if (hasDuplicateSubstring(that.pos, 'data')) {
						const pt = that.pos.replace(/\r?\n/g, '')
						const pos = pt.replace(/"code":200,"message":"SUCCESS","data":/g, '');
						const ps = pos.replace(/[{}""]/g, '') + '"}';
						const rs = '{"code":200,"message":"SUCCESS","data":"'
						that.pos = rs + ps
					}
					const po = JSON.parse(that.pos)
					console.log(po, '111')
					if (po.code == 200) {
						uni.hideLoading()
						that.typingQueue.push(po.data);
						// 如果当前没有打字机效果在进行，则开始处理队列  
						if (!that.isTyping) {
							that.processTypingQueue();
						}
					} else{
						this.creativeResults = ''
						uni.showToast({
							title: po.message,
							icon: 'none',
							duration: 2000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 2000);
					}
				});
			},
			goTextDetection(writing) {
				uni.navigateTo({
					url: '../save/save'
				})
			},
			// 打开会员
			openVip() {
				if (uni.getStorageSync('OS') !== 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					if (getApp().globalData.iosPay == 0) {
						uni.showModal({
							title: '提示',
							content: '由于相关规范，IOS功能暂不可用',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					} else if (getApp().globalData.iosPay == 1) {
						uni.navigateTo({
							url: '/pages/goods/goods'
						});
					}
				}
			},
			WaddAudio() {
				this.showMore = true;
			},
			//上传选择关闭
			close() {
				this.showMore = false;
			},
			

			//复制结果
			copyResults() {
			    uni.setClipboardData({
			    	data: this.creativeResults,
			    	showToast: true
			    });
			},
			onShareAppMessage(res) {
				const that = this
				this.showMore = false;
				// if (res.from === 'button') { // 来自页面内分享按钮
				// 	console.log(res.target, 'res.target')
				// }
				return {
					title: 'AI写作神器，一键改写变原创。',
					path: "pages/home/home?userid=" + that.userid,
					imageUrl: "https://iflytts.oss-cn-qingdao.aliyuncs.com/wxapp/xze/6.png",
					success: function(res) {
						console.log(
							"--------------转发成功--------------------",
							res,
							that.userid
						);
					}
				}
			},

			delWriting() {
				this.writing = ''
			},
		}
	}
</script>
<style lang="less">
	.page {
		width: 100%;
		height: calc(100vh);
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background: #F4F8FF;
	}

	.scroll-Y {
		width: 100%;
		height: 100%;
	}

	.page-view {
		width: 100%;
		height: 100%;
	}

	.title {
		width: 120%;
		height: 80rpx;
		margin: 0 0 0 -20px;
		box-sizing: border-box;
		padding: 0rpx 40rpx;
		display: flex;
		align-items: center;
		//   background-color: #F7F7F7;
		background-color: rgba(211, 238, 255, 0.5);
		font-size: 24rpx;
		color: #666666;
	}

	.context {
		width: 90%;
		margin: 0rpx auto;

		.context-tone {
			width: 100%;
			display: flex;
			flex-wrap: wrap;

			.context-tone-item {
				width: 18%;
				padding: 12rpx 14rpx;
				// background-color: #F7F7F7;
				border: 1px solid #3f96f7;
				border-radius: 24rpx;
				font-size: 22rpx;
				//   margin-left: 15rpx;
				//   margin-right: 30rpx;
				//   margin-bottom: 30rpx;
				margin: 5px 0 0 8.3px;
				color: #333333;
				text-align: center;
			}

			.context-tone-item-select {
				//   background-color: #4BB591;
				background-color: #3474ff;
				color: #fff;
			}
		}

		.context-tip {
			width: 100%;
			height: 90rpx;
			margin-top: 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.context-tip-left {
				font-size: 30rpx;
				color: #333333;
				display: flex;
				align-items: center;

				/deep/.context-tip-left-tip span {
					color: red;
					margin-left: 6rpx;
					vertical-align: sub;
				}
			}

			.context-tip-right {
				color: #999999;
				font-size: 24rpx;
			}
		}

		.context-title {
			width: 100%;
			height: 90rpx;
			font-size: 30rpx;
			color: #333333;
			margin-top: 10px;
			display: flex;
			align-items: center;

			/deep/.context-title-tip span {
				color: red;
				margin-left: 6rpx;
				vertical-align: sub;
			}
		}

		.context-textarea {
			width: 100%;
			height: 240rpx;
			// background-color: #F7F7F7;
			border: 1px solid #3f96f7;
			border-radius: 24rpx;
			position: relative;

			.context-textarea-input {
				width: 100%;
				height: 100%;
				box-sizing: border-box;
				padding: 22rpx 30rpx 0 30rpx;
				color: #333333;
				font-size: 28rpx;
			}

			.context-textarea-max {
				position: absolute;
				right: 40rpx;
				bottom: 20rpx;
				color: #999999;
			}
		}

		.button {
			width: 99%;
			height: 90rpx;
			background-color: rgba(52, 116, 255, 0.3);
			border-radius: 60rpx;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			font-size: 30rpx;
			margin: 40rpx auto 30rpx;
		}
	}

	.btn {
		display: flex;
		position: fixed;
		flex-direction: row;
		// background-color: rgba(211, 238, 255, 1);
		border-radius: 25px 25px 0 0;
		width: 100%;
		bottom: 0px;
		z-index: 99;
		margin-left: -20px;
	}

	.placeholder {
		height: 50%;
		padding-bottom: 200rpx;
	}

	.answer {
		width: 90%;
		margin: 0px auto;
		height: 90%;
		.answer-bott{
		    position: absolute;
		    left: 490rpx;
		    width: 168rpx;
		    height: 53rpx;
		    border-radius: 30rpx;
		    opacity: 1;
		    background: #EBEDF4;
		    font-size: 20rpx;
		    display: flex;
		    justify-content: center;
		    align-items: center;
		}

		.answer-fontLength {
			width: 100%;
			height: 60rpx;
			color: #333333;
			font-size: 24rpx;
			// display: flex;
			// align-items: center;
			//padding-left: 520rpx;
			position: absolute;
			left: 2%;
		}

		.answer-val {
			font-size: 21rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: -10px;
			color: #9e9e9e
		}

		.answer-value {
			width: 100%;
			height: 100rpx;
			color: #5490ff;
			font-size: 44rpx;
			line-height: 100rpx;
			// display: flex;
			// align-items: center;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.answer-textarea {
			position: relative;
			width: 100%;
			height: 90%;
			// background-color: #F7F7F7;
			background: white;
			border-radius: 24rpx;

			.answer-textarea-input {
				width: 100%;
				height: 93%;
				box-sizing: border-box;
				padding: 30rpx 30rpx 20rpx;
				color: #333333;
				font-size: 28rpx;
			}
		}
	}

	.tabbar {
		width: 100%;
		//   height: 10%;
		//   background-color: #fff;
		display: flex;
		box-sizing: border-box;
		justify-content: center;

		//   border-top: 1rpx solid #e5dbdb;
		.tabbar-item {
			width: 300rpx;
			height: 85rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			// flex-direction: column;
			font-family: PingFang SC;
			padding: 0 40rpx;
			font-weight: 500;
			color: #5490FF;
			line-height: 36rpx;
			font-size: 24rpx;
			border: solid 2rpx;
			margin: 0 12rpx;
			background:#BFD4FF;
			border-radius: 14rpx;
		}

		.tabbar-item:nth-child(2) {
			background: #5490ff;
			color:#ffffff;
		}
	}

	/deep/::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
		color: transparent;
	}

	.schedule-page {
		width: 100%;
		height: 100vh;
		position: fixed;
		background-color: rgba(128, 126, 126, 0.8);
		top: 0px;
		left: 0px;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 200;
	}

	.schedule-box {
		width: 62%;
		background-color: #fff;
		border-radius: 15rpx;
	}

	.schedule-text {
		text-align: center;
		line-height: 120rpx;
	}

	.schedule {
		width: 100%;
		height: 20rpx;
		margin: 20rpx 0rpx;
	}

	.schedule-number {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2979ff;
	}

	.lineBox {
		width: 90%;
		display: flex;
		justify-content: space-around;
		margin: 0px auto;
		height: 12rpx;
		border-radius: 24rpx;
		overflow: hidden;
	}

	.lineAnimation {
		height: 100%;
		background-color: #bbb9b9;
	}

	.lineAnimation-children {
		height: 100%;
		transition: all 0.5s;
		background-color: #2979ff;
	}

	.baifenbizdy {
		color: skyblue;
		font-size: 22px;
		align-items: center;
		justify-content: center;
		display: flex;
		margin-top: 7%;
	}

	.isshow {
		background-color: #fff;
		border-radius: 10px;
		width: 90%;
		height: 190px;
		left: 5%;
		position: relative;
		top: -70%;
		font-size: 50px;
		z-index: 10086;
		color: #1890ff;
		padding: 40px 0 0 0;
	}

	.box {
		width: 880px;
		background: #ffffff;
		position: relative;
		// height: 640px;
	}

	.textzdy {
		display: flex;
		font-size: 22px;
		margin: auto;
		color: grey;
		align-items: center;
		justify-content: center;
		padding-top: 2%;
	}

	.container {
		width: 90%;
		height: 7px;
		background-color: #fafafc;
		border-radius: 15px;
		margin-left: 5%;
		margin-top: 8%;
	}

	/* 内部加载部分样式 */
	.contentzdy {
		width: 100%;
		height: 7px;
		border-radius: 15px;
		background-color: #1890ff;
		text-align: center;
		line-height: 10px;
	}

	.jindu {
		margin-top: 1px;
	}
</style>